package com.whz.crypt.advice;

import com.whz.crypt.annotation.ResponseEncrypt;
import com.whz.crypt.config.CryptProperty;
import com.whz.crypt.config.CryptProperty.RsaProperty;
import com.whz.generic.crypt.aes.AesUtil;
import com.whz.generic.crypt.rsa.RsaUtils;
import com.whz.generic.json.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author whz
 */
@Slf4j
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final CryptProperty cryptProperty;

    public EncryptResponseBodyAdvice(CryptProperty cryptProperty, Environment environment) {
        this.cryptProperty = cryptProperty;
        cryptProperty.resolvePrivate(environment);
    }

    @Override
    public boolean supports(@NonNull MethodParameter returnType,
                            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return cryptProperty.isEnable() &&
               (Objects.requireNonNull(returnType.getMethod()).getAnnotation(ResponseEncrypt.class)) != null;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
        try {
            String content = JacksonUtils.toJsonString(body);
            String value = null;
            switch (cryptProperty.getCryptType()) {

            case AES: {
                value = aesEnc(content);
            }
            break;
            case RSA: {
                value = rsaEnc(content);
            }
            break;
            }
            if (cryptProperty.isPrintLog()) {
                log.info("http transport rsa encrypt data：{}，After encryption：{}", content, value);
            }
            return value;
        } catch (Exception e) {
            log.error("Encrypted data exception", e);
        }
        return body;
    }

    private String aesEnc(String content) {
        return AesUtil.encrypt(content, cryptProperty.getAesProperty().getSecretKey());
    }

    private String rsaEnc(String content) {
        String key = cryptProperty.getRsaProperty().getKey();
        if (cryptProperty.getRsaProperty().getKeyType() == RsaProperty.KeyType.PRIVATE) {
            return RsaUtils.encryptByPrivateKey(content, key);
        } else {
            return RsaUtils.encryptByPublicKey(content, key);
        }
    }
}